#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
按来源，统计数据不同的时间分布（支撑多个源同时统计）
思路：
需要给出导出量级、一天最多多少条、一个月最多多少条，以达到随机的目标
'''

import json
import sys

from apscheduler.schedulers.blocking import BlockingScheduler

from base import ExportAndTjBase
from models import MongoQueryConfig
from utils import Utils

reload(sys)
sys.setdefaultencoding('utf-8')


class ExportAndTj(ExportAndTjBase):
    def __init__(self, *args, **kwargs):
        super(ExportAndTj, self).__init__(*args, **kwargs)
        # todo other col
        # self.contact_col = self.db.p_col('contact')

    def handle_one_mongo_data(self, record_dic, save_result_dic=None):
        record_dic = Utils.decrypt_one_record(record_dic, need_decrypt=True, need_strf_time=True)
        # ["contact", "nameId", "name", "socialCreditCode", "regNumber", "contactType", "exportTime"]
        b2bPageUrl = record_dic.get('b2bPageUrl')
        nameId = record_dic.get('nameId')
        b2bSource = record_dic.get('b2bSource')
        b2bEnterpriseName = record_dic.get('b2bEnterpriseName')
        create_time = record_dic.get('create_time')
        import_update_time = record_dic.get('import_update_time')
        _id = record_dic.get('_id')

        must_exists_values = [b2bPageUrl, b2bSource, create_time]  # 这些字段都必须是非空值
        must_has_one_exists_values = []  # 这些字段必须最少有一个是非空值
        if self.is_values_has_none(must_exists_values):
            self.write_error_f.write('not all exists: {}'.format(must_exists_values))
        elif self.is_values_all_none(must_has_one_exists_values):
            self.write_error_f.write('not any exists {}'.format(must_has_one_exists_values))
        else:
            is_dc_flag = False  # 该数据是否需要导出
            create_time_day = create_time.split(' ')[0]
            create_time_month = create_time.rsplit('-', 1)[0]
            if create_time_day not in save_result_dic:
                save_result_dic[create_time_day] = 0
            if create_time_month not in save_result_dic:
                save_result_dic[create_time_month] = 0
            if save_result_dic[create_time_day] < save_result_dic['one_day_limit']:
                save_result_dic[create_time_day] += 1
                if save_result_dic[create_time_month] < save_result_dic['one_month_limit']:
                    save_result_dic[create_time_month] += 1
                    is_dc_flag = True
            if is_dc_flag:
                dc_ls = [b2bPageUrl, nameId, b2bSource, b2bEnterpriseName, create_time, import_update_time, _id]
                self.write_dc_f.write(
                    '{}\n'.format(json.dumps(dc_ls, ensure_ascii=False)))
                save_result_dic['total_need_dc'] -= 1
                if save_result_dic['total_need_dc'] < 0:
                    self.close_file()
                    exit()

        return save_result_dic

    def run(self):
        source_ls = [

        ]
        save_result_dic = {
            'one_day_limit': 10,  # 一天最多导出量
            'one_month_limit': 10,
            'total_need_dc': 1000,  # 总计需要导出数量

        }

        config = {
            MongoQueryConfig.col_name: 'business',
            MongoQueryConfig.filter: {
                'b2bSource': {'$in': [source_ls]}

            },
            MongoQueryConfig.projection: ["b2bPageUrl", "nameId", "b2bSource", "b2bEnterpriseName", "create_time",
                                          "import_update_time", "_id"]
        }
        result_dic = self.get_data_from_mongo(config, save_result_dic)


def run(abs_file_name):
    export_and_tj = ExportAndTj(abs_file_name)
    export_and_tj.main()


def scheduler_run(abs_file_name):
    scheduler = BlockingScheduler()
    scheduler.add_job(func=run, trigger='cron',
                      args=(abs_file_name,),
                      # day_of_week="sun",
                      hour='20', minute='52', id='dd_run')
    scheduler.start()


if __name__ == '__main__':
    file_name = 'business表多源不同时间段随机导出'
    # py文件名+file_name+小时时间
    abs_file_name = Utils.generate_abs_path(file_name, current_py_path=__file__)

    run(abs_file_name)
    # scheduler_run(abs_file_name)
